import { reqGameList, reqGameTotal } from "@/api/main";
import { reqGameSettingShow } from "@/api/setting";
import { STORE_PREFIX } from "@/utils/constant";
import { cloneDeep } from "lodash-es";
import { defineStore } from "pinia";

export const useGameStore = defineStore(
  `${STORE_PREFIX}game_store`,
  () => {
    const gameList = ref<GameListMo[]>([]);
    const gameLeft = ref<GameLeftMo[]>([]);
    const gameTotal = ref<GameTotalMo[]>([]);

    const setLotteryGame = (v: GameTotalMo) => {
      const list = cloneDeep(gameTotal.value);
      for (let i = 0; i < list.length; i++) {
        if (Number(list[i].LotteryId) === Number(v.LotteryId)) {
          list[i] = cloneDeep(v);
        }
      }
      gameTotal.value = cloneDeep(list);
    };

    const actionGameLeft = async () => {
      try {
        const res = await reqGameList();
        gameLeft.value = res.data.map(item => ({ ...item, Checked: false }));
      } catch (error) {
        console.log(error);
      }
    };
    const actionGameList = async () => {
      try {
        const res = await reqGameSettingShow();
        gameList.value = res.data;
        return res.data;
      } catch (error) {
        console.log(error);
        return [];
      }
    };
    const actionGameTotal = async () => {
      try {
        const res = await reqGameTotal();
        res.data.sort((a, b) => {
          if (a.LotterySort !== b.LotterySort) {
            return a.LotterySort - b.LotterySort;
          }
          return a.LotteryId - b.LotteryId;
        });
        gameTotal.value = res.data;
        return res.data;
      } catch (error) {
        console.log(error);
      }
    };
    return {
      gameList,
      gameLeft,
      gameTotal,
      setLotteryGame,
      actionGameList,
      actionGameLeft,
      actionGameTotal
    };
  },
  {
    persist: {
      storage: sessionStorage
    }
  }
);
